package com.aids_malaria.ui.setting;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.aids_malaria.R;
import com.aids_malaria.adapter.AccountManagerRoleAdapter;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.util.LiteOrmUtil;
import com.aids_malaria.http.response.Role;
import com.aids_malaria.http.response.User;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.idcardcamera.camera.IDCardCamera;
import com.aids_malaria.util.AuthUtil;
import com.aids_malaria.util.DisplayUtil;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.ConfirmDialog;
import com.aids_malaria.widget.titlebar.TitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class AccountManagerCreateEditActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.rv_role)
    RecyclerView rv_role;
    @BindView(R.id.et_login_account)
    EditText et_login_account;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.et_user_name)
    EditText et_user_name;
    @BindView(R.id.et_contact_phone)
    EditText et_contact_phone;

    public static final String KEY_IS_CREATE = "is_create";
    public static final String KEY_USER = "user";

    private boolean isCreate;
    private User mUser;

    private List<Role> mData = new ArrayList<>();
    private AccountManagerRoleAdapter accountManagerRoleAdapter;

    private String preAccount = "";
    private String prePwd = "";
    private String preName = "";
    private String prePhone = "";
    private String prerole = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_account_manager_create_edit;
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getIntent().getExtras();
        if(null != bundle){
            isCreate = bundle.getBoolean(KEY_IS_CREATE);
        }
        if(isCreate){
            initTitleBar(title_bar,getString(R.string.user_create));
            mUser = new User();
            mUser.setRole_id("");
        }else{
            initTitleBar(title_bar,getString(R.string.user_edit));
            et_login_account.setEnabled(false);
            et_login_account.setBackground(getResources().getDrawable(R.drawable.shape_rounded_gray));
            mUser = (User) bundle.getSerializable(KEY_USER);
            et_login_account.setText(mUser.getUser_code());
            et_user_name.setText(mUser.getUser_name());
            et_password.setText(mUser.getPassword());
            et_contact_phone.setText(mUser.getContact_pn());

            preAccount = mUser.getUser_code();
            preName = mUser.getUser_name();
            prePwd = mUser.getPassword();
            prePhone = mUser.getContact_pn();
        }
        initRecycleView();
        getRole();
    }

    @Override
    public void back() {
        String curAcc = et_login_account.getText().toString().trim();
        String curName = et_user_name.getText().toString().trim();
        String curPwd = et_password.getText().toString().trim();
        String curPhone = et_contact_phone.getText().toString().trim();
        String curRole = "";
        for (int i = 0; i < mData.size(); i++) {
            Role role = mData.get(i);
            if (role.isCheck()){
                curRole = role.getRole_id();
            }
        }

        //角色数组有数据，但是之前没分配角色，有选中就是有修改
        Boolean preNoRole = (prerole == null) && !StringUtil.isEmpty(curRole);
        //角色数据有数据，之前有分配角色，判断当前选中的角色是否与之前的一样
        Boolean preHasRole = !prerole.equals(curRole);
        Boolean showTip = ( (isCreate && (!StringUtil.isEmpty(curAcc) || !StringUtil.isEmpty(curName)
                || !StringUtil.isEmpty(curPwd) || !StringUtil.isEmpty(curPhone) || (mData.size()> 0 && !StringUtil.isEmpty(curRole))))
            || (!isCreate && ( !preAccount.equals(curAcc) || !preName.equals(curName) || !prePwd.equals(curPwd)
        || !prePhone.equals(prePhone) || (mData.size()> 0 && (preNoRole || preHasRole)))));

        if (!showTip){
            finish();
            return;
        }
        String tipString = isCreate ? getString(R.string.tip_data_add):getString(R.string.tip_data_modify);
        ConfirmDialog.newInstance(true, getString(R.string.hint), tipString)
                .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void confirm() {
                        finish();
                    }
                })
                .setOutCancel(true)
                .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                .show(getSupportFragmentManager());
    }

    private void initRecycleView() {
        rv_role.setLayoutManager(new GridLayoutManager(mContext,2));
        accountManagerRoleAdapter = new AccountManagerRoleAdapter(mContext,R.layout.item_account_manager_role,mData);
        rv_role.setAdapter(accountManagerRoleAdapter);
        accountManagerRoleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                for (int i=0; i<mData.size(); i++) {
                    if(position == i){
                        mData.get(i).setCheck(!mData.get(i).isCheck());
                    }else{
                        mData.get(i).setCheck(false);
                    }
                }
                accountManagerRoleAdapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick({R.id.tv_confirm})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.tv_confirm:
                String userCode = et_login_account.getText().toString().trim();
                String userName = et_user_name.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                String contactPn = et_contact_phone.getText().toString().trim();
                if(StringUtil.isEmpty(userCode) || StringUtil.isEmpty(userName) ||
                    StringUtil.isEmpty(password) || StringUtil.isEmpty(contactPn)){
                    ToastUtil.showToast(getString(R.string.input_null));
                    return;
                }
                String roleId = "";
                for (int i=0; i<mData.size(); i++) {
                    if(mData.get(i).isCheck()){
                        roleId = mData.get(i).getRole_id();
                    }
                }
                if(StringUtil.isEmpty(roleId)){
                    ToastUtil.showToast(getString(R.string.user_null));
                    return;
                }
                mUser.setUser_code(userCode);
                mUser.setUser_name(userName);
                mUser.setPassword(password);
                mUser.setContact_pn(contactPn);
                mUser.setRole_id(roleId);
                String dataJson = GsonUtil.beanToJson(mUser);
                LogUtil.d("dataJson:------------" + dataJson);
                if(isCreate){
                    saveUser("1", dataJson);
                }else{
                    if (!AuthUtil.isHaveUpdateAuthByCode(Constant.SETTING_ROLE_MANAGER)){
                        ToastUtil.showNoPermission();
                        return;
                    }
                    saveUser("2", dataJson);
                }
                break;
        }
    }

    /**
     * 获取角色数据
     *
     */
    private void getRole() {
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getRole("")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<Role>>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(List<Role> data) throws Exception {
                        mData.clear();
                        mData.addAll(data);
                        for (int i=0; i<mData.size(); i++) {
                            if(mUser.getRole_id().equals(mData.get(i).getRole_id())){
                                mData.get(i).setCheck(true);
                                prerole = mData.get(i).getRole_id();
                            }
                        }
                        accountManagerRoleAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

    /**
     * 保存用户数据
     * @param busy_type  保存类型 1插入 2更改 3 删除
     * @param data  (各数据字段定义见数据库TBL_COM_USER表定义)： 该用户数据（json格式）
     * @return
     */
    private void saveUser(String busy_type, String data) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), data);
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).saveUser(busy_type, requestBody)
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<Object>() {

                    @Override
                    protected void onStart() {
                        getLoadingDialog().show();
                    }

                    @Override
                    protected void onSuccess(Object data) throws Exception {
                        ToastUtil.showToast(getString(R.string.operate_success));

                        setResult(200);
                        finish();
                    }

                    @Override
                    protected void onFinish() {
                        getLoadingDialog().dismiss();
                    }
                });
    }

}
